package com.youdoneed.application;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Ewing
 * @since 2017-05-07
 **/
@Component
public class ZuulFallback implements ZuulFallbackProvider {
    public static final String FALLBACK_TEXT = "服务超时，请重试。";

    @Override
    public String getRoute() {
        return null;
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.REQUEST_TIMEOUT;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.REQUEST_TIMEOUT.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.REQUEST_TIMEOUT.name();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(FALLBACK_TEXT.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return httpHeaders;
            }
        };
    }
}
